//ajax热搜

displayTodayHotSearch();
/*左下角更多infopad js - start*/
document.getElementById("showmore").addEventListener("click", function (event) {
    var infoPad = document.getElementById("infopad");

    // 阻止点击按钮时事件冒泡，防止立刻触发文档点击事件
    event.stopPropagation();

    // 切换显示或隐藏
    if (infoPad.style.display === "none" || infoPad.style.display === "") {
        infoPad.style.display = "block";
    } else {
        infoPad.style.display = "none";
    }
});

// 点击页面其他部分隐藏 infoPad
document.addEventListener("click", function () {
    var infoPad = document.getElementById("infopad");
    infoPad.style.display = "none"; // 点击页面任何其他部分时隐藏
});

// 阻止点击 infoPad 本身时触发隐藏
document.getElementById("infopad").addEventListener("click", function (event) {
    event.stopPropagation();
});

/*搜索框js - start*/
// 获取输入框和提示元素
const searchInput = document.getElementById('soinput');
const searchTips = document.getElementById('so_tips');

// 当输入框获得焦点时，显示提示
searchInput.addEventListener('focus', function () {
    searchTips.style.display = 'block';
});

// 当输入框失去焦点时，隐藏提示
searchInput.addEventListener('blur', function () {
    // 使用setTimeout是为了确保点击事件能够在失去焦点之后再进行判断
    setTimeout(function () {
        // 判断点击的目标是否在searchTips内部
        if (!searchTips.contains(document.activeElement)) {
            searchTips.style.display = 'none';
        }
    }, 100);
});

// 当点击searchTips时，不隐藏提示
searchTips.addEventListener('mousedown', function (event) {
    event.preventDefault(); // 阻止失去焦点事件触发
});


// 清除指定名称的 cookie
function deleteCookie(cookieName) {
    // 设置 cookie 的过期时间为一个过去的时间来删除它
    document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
    Qmsg.success("已退出当前账号，自动跳转中 . . .",{
        position: 'center'
    });
    setTimeout(function() {
        window.location.href = 'index.php';
    }, 1700);
}

// 联系官方弹窗
function contactMsg(msginfo) {
    Qmsg.success(msginfo,{
        position: 'center'
    });
}

//输入框搜索
function search() {
    var inputVal = document.getElementById('soinput').value.trim();  // 获取输入框内容并去除空格

    if (inputVal) {
        window.location.href = '/?so=' + encodeURIComponent(inputVal);
    } else {
        Qmsg.info("输入框不能为空！");
    }
}

// 点击按钮触发搜索
document.querySelector('.search-button').addEventListener('click', function() {
    search();
});

// 按下回车键触发搜索
document.getElementById('soinput').addEventListener('keypress', function(event) {
    if (event.key === 'Enter') {
        search();
    }
});



//ajax updateSearch
$.ajax({
    url: '/api/action.php?type=sohistory',
    method: 'POST',
    data: {
        uid: uid,
        ...(typeof meuid !== 'undefined' && meuid !== null ? { meuid: meuid } : {}),
    },
    success: function (response) {
        if(!uid){
            return;
        }
        if (window.location.pathname.includes('profile.php')) {
            if(!meuid){
                return;
            }
            // profile有uid未登录页 2024-10-13
            
        }


        //console.log(meuid)
        updateSearchHistory(response);
    },
    error: function (xhr, status, error) {
        //console.log("Error: " + error);
    }
});

function updateSearchHistory(searchHistory) {

    var historyPad = $('.search_history_pad');

    historyPad.empty();

    if (searchHistory.length === 0) {
        historyPad.append('<span class="search_history no_search_history">还没有搜索记录 ~</span>');
    } else {
    searchHistory.forEach(function (historyItem) {
        var historyElement = $('<span class="search_history"></span>')
        .text(historyItem.search_keywords)
        .attr('data-id', historyItem.id) // 添加 data-id 属性
        .attr('onclick', `window.location.href='/?so=${encodeURIComponent(historyItem.search_keywords)}'`);

        historyPad.append(historyElement);
    });
    }
}


$(document).on('click', '.search_close_icon', function(event) {
    event.stopPropagation(); // 阻止点击事件冒泡

    // 获取对应的搜索历史元素
    const historyElement = $(this).closest('.search_history');
    var id = historyElement.data('id'); // 获取 data-id

    historyElement.remove(); // 移除对应的历史元素
    if ($('.search_history').length === 0) {
        $('.search_history_pad').append('<span class="search_history no_search_history">还没有搜索记录 ~</span>');
    }
    // 发送 AJAX 请求
    $.ajax({
        url: '/api/action.php?type=hideso', // API 接口地址
        method: 'POST', // 请求方式
        data: {
            uid: uid,
            id: id,
        },
        success: function(response) {
            //console.log(response);

        },
        error: function(xhr, status, error) {
            //console.log("Error: " + error);
        }
    });
});


//ajax实时搜索
//更新内容块变量存储
/*var so_parentElement;
var originalContent;
$('#soinput').on('click', function() {
    if (!so_parentElement) {
        so_parentElement = $('#so_tips').clone(); // 获取 #so_tips 的克隆副本
        originalContent = so_parentElement.html(); // 保存初始 HTML 内容
        if ($('#soinput').val()) {
            $('#so_tips').children().not('.info_container').remove();
            $('.info_container').show();

            fetchSearchKeywords($('#soinput').val().trim()); // 调用 AJAX 请求
        }
    }
});*/
$('#soinput').mouseenter(function() {
    var inputValue = $(this).val().trim();

    if (inputValue.length > 0) {
        fetchSearchKeywords(inputValue);
    }
});

$('#soinput').on('input', function() {
    var inputValue = $(this).val().trim();

    if (inputValue.length > 0) {
        fetchSearchKeywords(inputValue);
    } else {
        $('.info_container').hide();
        $('#so_tips').children().not('.info_container').show();
    }
});

function fetchSearchKeywords(inputValue) {
    $.ajax({
        url: '/api/action.php?type=sokeywords',
        method: 'POST',
        data: {
            keywords: inputValue
        },
        success: function(response) {
            //console.log(response);
            $('.info_container').show();
            $('#so_tips').children().not('.info_container').hide();

            // 添加新的搜索结果
            if (response.length > 0){
                $('.info_container').empty();
                response.forEach(function(keyword) {
                    var infoBtn = $('<div class="info_btn"></div>')
                        .text(keyword.search_keywords)
                        .attr('onclick', `window.location.href='/?so=${encodeURIComponent(keyword.search_keywords)}'`);

                    if (inputValue.length > 0) {
                        // 遍历关键词中的每个字符
                        var coloredText = '';
                        for (var i = 0; i < keyword.search_keywords.length; i++) {
                            var char = keyword.search_keywords[i];
                            if (inputValue.includes(char)) {
                                coloredText += '<span style="color: #333;">' + char + '</span>';
                            } else {
                                coloredText += char;
                            }
                        }
                        // 将带有颜色标记的关键词添加到 infoBtn 中
                        infoBtn.html(coloredText);
                    }
                    $('.info_container').append(infoBtn);
                });
            }else{
                $('.info_container').empty();
                var infoBtn = $('<div class="info_btn" style="color: #333"></div>')
                    .text(inputValue)
                    .attr('onclick', `window.location.href='/?so=${encodeURIComponent(inputValue)}'`);
                $('.info_container').append(infoBtn);
            }
        },
        error: function(xhr, status, error) {
            console.log("Error: " + error);
        }
    });
}

//ajax获取热搜榜
function displayTodayHotSearch() {
    $.ajax({
        url: '/api/action.php?type=hotkeywords',
        method: 'GET',
        success: function(response) {
            if (response && response.length > 0) {
                var hotSearchContainer = $('#todayHot');

                response.reverse().forEach(function(keyword, index) {
                    var rank = response.length - index;
                    var infoBtn = $('<div class="info_btn"></div>');
                    var rankSpan = $('<span class="rank">' + rank + '、</span>');
                    if (rank <= 3) {
                        rankSpan.css({
                            color: '#f26d5f',
                            fontWeight: 'bold',
                            fontStyle: 'italic'
                        });
                    } else {
                        rankSpan.css({
                            color: '#ff8200'
                        });
                    }
                    var keywordText = keyword.search_keywords;
                    infoBtn.attr('onclick', `window.location.href='/?so=${encodeURIComponent(keyword.search_keywords)}'`);
                    infoBtn.append(rankSpan);
                    infoBtn.append(keywordText);

                    hotSearchContainer.after(infoBtn);
                });
            } else {
                var hotSearchContainer = $('#todayHot');
                var infoBtn = $('<div class="info_btn"></div>');
                var rankSpan = $('<span class="rank">1、</span>');
                rankSpan.css({
                    color: '#f26d5f',
                    fontWeight: 'bold',
                    fontStyle: 'italic'
                });
                var keywordText = '今天还没有热搜 ~';

                infoBtn.append(rankSpan);
                infoBtn.append(keywordText);

                hotSearchContainer.after(infoBtn);
            }
        },
        error: function(xhr, status, error) {
            console.error('Error fetching today\'s hot search:', error);
        }
    });
}



// 点击删除图标时
$('.sohistsdelete').on('click', function() {
    // 隐藏删除图标
    $(this).hide();
    $('.sohistscomplete, .sohiststclear').show();

    if ($('.no_search_history').length === 0) {
        $('.search_history').removeAttr('onclick');
        $('.search_history').addClass('search_clear');
        $('.search_history').each(function() {
            $(this).prepend('<img src="/static/img/close-black.svg" class="search_close_icon" alt="Close">');
        });
    }
});

// 点击完成图标时
$('.sohistscomplete').on('click', function() {
    // 隐藏完成图标
    $(this).hide();
    $('.sohiststclear').hide();
    // 显示删除图标
    $('.sohistsdelete').show();

    $('.search_history').removeClass('search_clear');
    $('.search_history').find('img.search_close_icon').remove();

    // 遍历每个 .search_history 元素
    $('.search_history').each(function(index, element) {
        var content = $(element).text().trim();
        var encodedContent = encodeURIComponent(content);

        // 设置 onclick 属性
        $(element).attr('onclick', `window.location.href='/?so=${encodedContent}'`);
    });

});

$('.sohiststclear').on('click', function() {
    $(this).hide();
    $('.sohistscomplete').hide();
    // 显示删除图标
    $('.sohistsdelete').show();
    $('.search_history_pad').empty();
    $('.search_history_pad').append('<span class="search_history no_search_history">还没有搜索记录 ~</span>');
    // 发送 AJAX 请求
    $.ajax({
        url: '/api/action.php?type=hideso', // API 接口地址
        method: 'POST', // 请求方式
        data: {
            uid: uid, // 发送用户 ID
        },
        success: function(response) {
            // 处理成功响应
            /*$('.search_history_pad').empty();*/
        },
        error: function(xhr, status, error) {
            // 处理错误
            //console.log("Error: " + error);
            //alert('请求失败，请稍后重试。');
        }
    });
});



